﻿using Common.WeiXin;
using MobileWeb.App_Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace WeiXin
{
    /// <summary>
    /// WeiXinHandler 的摘要说明
    /// </summary>
    public class WeiXinHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (!WeiXinHelper.VerifySignature()) { return; }
            string xml = WeiXinHelper.GetReceiveXml();
            string type = GetMessageType(xml);
            if (type == null)
            {
                if (!string.IsNullOrEmpty(context.Request["echostr"])) { context.Response.Write(context.Request["echostr"]); }  //接口接入
                return;
            }
            switch (type)
            {
                case "event":
                    new WeiXinEventHandle(context, xml);
                    break;
                case "text":
                    new WeiXinTextHandle(context, xml);
                    break;
            }
        }
        /// <summary>
        /// 获取消息类型
        /// </summary>
        /// <returns></returns>
        string GetMessageType(string xml)
        {
            if (string.IsNullOrEmpty(xml)) { return null; }
            Match match = Regex.Match(xml, "<MsgType><!\\[CDATA\\[(.+)\\]\\]></MsgType>", RegexOptions.IgnoreCase);
            if (match.Length == 0) { return null; }
            return match.Groups[1].Value.ToLower();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}